<?php

class InventoryController extends Controller {

    public function actionIndex() {

        die('test');
    }

    public function actionWarehouse($wid = false, $html = false, $mail = false, $options = false) {
        if ($options) {
            $options = json_decode($options, true);
            $cost = $options['cost'];
            $zero = $options['zero'];
            $reorder = $options['reorder'];
        } else {
            $cost = false;
            $zero = false;
            $reorder = false;
        }
        if ($wid) {
            if ($cost)
                $list = Yii::app()->db->createCommand('SELECT inv.partno, inv.averagecost as cost, inv.description,SUM( qty ) - SUM( qtyout ) AS qty
FROM  `tbl_inventory` AS inv,  `tbl_inventoryact` AS invact
WHERE inv.partno = invact.partno and invact.type = "I" and warehouse=:warehouse GROUP BY partno ')->bindValue('warehouse', $wid)->queryAll();
            else
                $list = Yii::app()->db->createCommand('SELECT inv.partno, inv.description,SUM( qty ) - SUM( qtyout ) AS qty
FROM  `tbl_inventory` AS inv,  `tbl_inventoryact` AS invact
WHERE inv.partno = invact.partno and invact.type = "I" and warehouse=:warehouse GROUP BY partno ')->bindValue('warehouse', $wid)->queryAll();
            $result = array();
            foreach ($list as $partno) {
                $qtyData = false;

                if ($reorder) {
                    $criteria = new CDbCriteria();
                    $criteria->addColumnCondition(array('partno' => $partno['partno'], 'warehouse' => $wid));
                    $qtyData = Inventoryquanity::model()->find($criteria);
                }
                $sum = $partno['qty'];
                if ($sum || $zero) {
                    $result[$partno['partno']]['partno'] = $partno['partno'];

                    $result[$partno['partno']]['description'] = $partno['description'];
                    $result[$partno['partno']]['qty'] = $sum;
                    if ($cost)
                        $result[$partno['partno']]['cost'] = $partno['cost'];
                    if ($qtyData) {
                        $result[$partno['partno']]['minqty'] = $qtyData->minqty;
                        $result[$partno['partno']]['reorder'] = $qtyData->reorder;
                    } else {
                        $result[$partno['partno']]['minqty'] = 'N/A';
                        $result[$partno['partno']]['reorder'] = 'N/A';
                    }
                }
            }
            if ($html) {
                $this->layout = '//layout/space';
                $this->render('warehouseResult', array('data' => $result, 'wid' => $wid, 'cost' => $cost, 'reorder' => $reorder));
            } else {
                $string = '';
                $heading = 'PartNo , Description , QTY';
                if ($cost) {
                    $heading .=', Avg Cost, Total Cost';
                }
                if ($reorder)
                    $heading .= ', Min QTY , Reorder QTY';
                $heading.=PHP_EOL;
                $string.=$heading;
                foreach ($result as $row) {
                    $desc = str_replace(',', '', $row['description']);
                    $string.=$row['partno'] . ' , ' . $desc . ' , ' . $row['qty'];
                    if ($cost) {
                        $string .= ' , ' . number_format($row['cost'], 2, '.', '') . ',' . number_format($row['qty'] * $row['cost'], 2, '.', '');
                    }
                    if($reorder){
                          $string.= ' , ' . $row['minqty'] .' , ' . $row['reorder'];
                    }
                    $string.=PHP_EOL;
                }


                $reportName = 'warehouse-report-' . $wid . '-' . date('Y-m-d H:i:s') . '.csv';
               
                $f = fopen("csv/$reportName", 'w+');
                if ($f !== false) {
                    fwrite($f, $string);
                }
                fclose($f);

                if ($mail) {
                    $body = $_POST['message'];
                    $address = $_POST['email'];
                    $emailArray = explode(',', $address);
                    $subject = $_POST['subject'];

                    $attachment = 'csv/' . $reportName;
                    if (!EmailUtil::sendEmail($subject, $emailArray, $body, $attachment)) {
                        $result = array('success' => false, 'msg' => $mail->ErrorInfo);
                        echo json_encode($result);
                    } else {
                        $log = new PrintLog();
                        $log->date = date('Y-m-j');
                        $log->time = date('h-i-s');
                        $log->type = 'Warehouse Report';
                        $log->number = $reportName;
                        $log->emailto = $_POST['email'];
                        $log->print = 'Yes';
                        $log->save();
                        $result = array('success' => true, 'msg' => 'Message sent!');
                        echo json_encode($result);
                    }
                } else {
                    Yii::app()->fileHelper->forceDownload("csv/$reportName");
                }
            }
        } else {
            $data = array();

            $presidentContract = Employees::model()->findByPk('1109');
            if ($presidentContract != null) {
                $data[$presidentContract->workemail] = 'Greg Cahoe' . ' - ' . $presidentContract->workemail;
            }

            if (empty($data))
                $data = array('N/A', 'N/A');
            outputJsByList($data, 'contacts');
            $this->render('warehouse');
        }
    }

}

